mybatis系列之初识mybatis

您所在的位置:网站首页 銭0961fa51 a52 a71 mybatis系列之初识mybatis

mybatis系列之初识mybatis

#mybatis系列之初识mybatis | 来源: 网络整理| 查看: 265

hello~各位读者新年好,我是鸭血粉丝(大家可以称呼我为「阿粉」),一位立志要成为码王的男人!

说在前面的话

今天开始,阿粉准备把 mybatis 的知识梳理一遍,为什么梳理 mybatis 呢?因为 mybatis 的源码最简单啊(说什么大实话)。no~no~no~,是因为现在的这些框架都和 springboot 整合在一起了,用起来是方便了,但是其中的原理就越不了解了。所以阿粉整理几篇 mybatis 的文章分享给大家,配合代码案例,希望大家有所收获。另外因为这是第一篇,所以代码量相对来说比较多,希望大家耐下看下去,毕竟阿粉也是下了一番功夫的,绝对是原创,如有雷同,肯定是他们抄袭阿粉的。

好了,话不多说,我们直接进入正题。

1 mybatis为我们做了哪些事情 使用连接池对连接进行管理 :连接池,这个不多说。 SQL 和代码分离,集中管理 :主要是 mapper.xml 文件,专门用来配置sql语句。 重复 SQL 的提取 :比如标签。 参数映射和动态 SQL :比如 等。 结果集映射 :查询结果后会映射成对象。 缓存管理 :一级缓存和二级缓存。 插件机制:分页插件等。

这些阿粉会在 mybatis 系列文章中都会讲到。

2 准备工作(小demo,配合讲解)

先整体说下需要有哪些东西:

pom.xml 引入 mybatis 引入 jar 包。 mybatis-config.xml 配置文件。 mapper 接口和 mapper.xml 文件。 测试类。

2.1 pom.xml 文件 ,因为不和 spring/springBoot 集成,所以引入的 jar 包比较少。

12345678910 org.mybatis mybatis 3.5.1 mysql mysql-connector-java 8.0.16

2.2 mybatis-config.xml文件(重点) ,db.properties 为数据库的配置信息,不单独贴出来。

1234567891011121314151617181920212223242526

2.3 mapper接口和 mapper.xml,Fruit为水果 pojo 类,只有id和name两个属性,不单独贴出来

123public interface FruitMapper { Fruit findById(Long id); } 12345678 id,name select from fruit where id =#{id}

2.4 测试方法(重点)

12345678910111213141516public class MybatisTest { @Test public void testSelect() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); try { FruitMapper mapper = session.getMapper(FruitMapper.class); Fruit fruit = mapper.findById(1L); System.out.println(fruit); } finally { session.close(); } } }

2.5 执行测试方法的结果

12345678Created connection 2014838114. Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7817fd62] ==> Preparing: select id,name from fruit where id =? ==> Parameters: 1(Long)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3